package com.mask.lego.product.exception;

import com.mask.lego.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 统一异常处理
 * @author hx
 * @since 2021/12/6 5:13 下午
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.mask.lego.product.app")
public class LegoMallException {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验异常{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            errorMap.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(400,"数据校验异常").put("data",errorMap);
    }


}
